    var form = layui.form, table = layui.table, $ = layui.jquery, upload = layui.upload, id = getQueryVariable("id");

    $('#editor-form').find('input,textarea,select').attr('disabled',true);
    //表单初始值，修改时调用
    if (id != "") {
        form.val("editor-form", {
            "contact": "进入查看明细",
        })
    }
    form.render();

    let deleteAnnexIds = [];
    //报价产品明细数据
    let detailList = [];
    //费用数据
    let costList = [];
    //附件明细数据
    let annexList = [];
    //操作日志数据
    let operationLog = [];

    //订单操作标签 有权限:false 无权限:true
    let isOrderInquiryTab = getAllRolesByCurr("OrderInquiryTab");

    layer.ready(function () {
        //合同总额 无权限需隐藏
        if(!isOrderInquiryTab){
            $(".Authority-Label").hide();
        }
        //获取详情信息
        $.ajax({
            url:"exportContract/detail?id="+id,
            success:function(res){
                if(res.status == 200){
                    //主表信息赋值
                    if(null != res.data){
                        //主表数据
                        let vo =  res.data;
                        form.val("editor-form", {
                            "billNo" : vo.billNo,
                            "customerName" : vo.customerName,
                            "customerContactName" : vo.customerContactName,
                            "contactEmail" : vo.contactEmail,
                            "customerContactNo" : vo.customerContactNo,
                            "signingDate" : vo.signingDate,
                            "signingCompanyName" : vo.signingCompanyName,
                            "bankName" : vo.bankName,
                            "transitPlaceName" : vo.transitPlaceName,
                            "destinationName" : vo.destinationName,
                            "currency" : vo.currency,
                            "usdRate" : vo.usdRate,
                            "rmbRate" : vo.rmbRate,
                            "carryTime" : vo.carryTime,
                            "modeOfTradeStr" : vo.modeOfTradeStr,
                            "modeOfTransport" : vo.modeOfTransport,
                            "priceTermsName" : vo.priceTermsName,
                            "paymentTerm" : vo.paymentTerm,
                            "salesmanName" : vo.salesmanName,
                            "businessModelName" : vo.businessModelName,
                            "rechargeOccupancyStr" : vo.rechargeOccupancyStr,
                            "isDeclareStr" : vo.isDeclareStr,
                            "shipmentInBatchesStr" : vo.shipmentInBatchesStr,
                            "whetherToSupportStr" : vo.whetherToSupportStr,
                            "whetherToReplenishStr" : vo.whetherToReplenishStr,
                            "whetherToPurchaseStr" : vo.whetherToPurchaseStr,
                            "whetherCreditGuaranteeStr" : vo.whetherCreditGuaranteeStr,
                            "creditGuaranteeAmount" : vo.creditGuaranteeAmount,
                            "containerType" : vo.containerType,
                            "paymentTypeName" : vo.paymentTypeName,
                            "customerAccountingPeriod" : vo.customerAccountingPeriod,
                            "shippingMarkStr" : vo.shippingMarkStr,
                            "operator" : vo.operator,
                            "advancePaymentRatio" : vo.advancePaymentRatio,
                            "advancePaymentAmount" : vo.advancePaymentAmount,
                            "totalContractAmount" : vo.totalContractAmount,
                            "customerLevelName" : vo.customerLevelName,
                            "creditQuota" : vo.creditQuota,
                            "customerComplaintNo" : vo.customerComplaintNo,
                            "countryName" : vo.countryName,
                            "city" : vo.city,
                            "memo" : vo.memo
                        });

                        //产品明细数据
                        if(null != res.data.detailList && res.data.detailList.length > 0){
                            detailList = res.data.detailList;
                            table.reload('storageproductstableid',{data : detailList});
                        }

                        //费用数据
                        if(null != res.data.costList && res.data.costList.length > 0){
                            //权限判断
                            if (!isOrderInquiryTab) {
                                costList = [];
                            } else {
                                costList = res.data.costList;
                            }
                            table.reload('costtableid',{data : costList});
                        }

                        //附件
                        if(null != res.data.annexList && res.data.annexList.length > 0){
                            //权限判断
                            if (!isOrderInquiryTab) {
                                annexList = [];
                            } else {
                                annexList = res.data.annexList;
                            }
                            table.reload('attachmenttableid',{data : annexList});
                        }

                        //日志
                        if(!isEmpty(res.data.logList) && res.data.logList.length > 0){
                            //权限判断
                            if (!isOrderInquiryTab) {
                                operationLog = [];
                            } else {
                                operationLog = res.data.logList;
                            }
                            table.reload('logtableid',{data:operationLog});
                        }

                    }
                    return false;
                }else {
                    layer.msg(res.msg, {icon: 5});
                }
            }
        });
    })
    //--产品信息
    table.render({
        elem: '#storageproducts',
        id: 'storageproductstableid',
        data: detailList,
        toolbar: '#storageproductstoolbar',
        totalRow: true,
        cols: [[
            {field: 'numbers',width: 50,type:'numbers',title:'序号', totalRowText: '合计'},
            {field: 'img', title: '产品图片', width: 120, align: 'center', templet: '#imgTpl'},
            {field: 'productCode', width: 120, title: '产品编码'},
            {field: 'specificationCode', width: 120, title: '规格编码'},
            {field: 'productEname', width: 120, title: '英文名称'},
            {field: 'productCdesc', width: 120, title: '中文描述'},
            {field: 'productEdesc', width: 120, title: '英文描述'},
            {field: 'productNum', width: 120, title: '数量', totalRow: true},
            {field: 'productUnitName', width: 120, title: '单位'},
            {field: 'unitPrice', width: 80, title: '单价'},
            {field: 'moneySubtotal', width: 120, title: '金额小计', totalRow: true},
            {field: 'deliveryDate', width: 150, title: '要求交货日期'},
            {field: 'specificationExplanation', width: 120, title: '规格说明'},
            {field: 'clientProductNo', width: 120, title: '客户货号'},
            {field: 'productCname', width: 120, title: '中文名称'},
            {field: 'customerInvoiceGoodsName', width: 120, title: '客户开票货物名称'},
            {field: 'customerInvoiceSpecModel', width: 120, title: '客户开票规格型号'},
            {field: 'customerMaterialsCode', width: 120, title: '客户物料编码'},
            {field: 'color', width: 120, title: '颜色'},
            {field: 'customsCode', width: 120, title: '海关编码'},
            {field: 'nameCustomsDeclaration', width: 120, title: '报关品名'},
            {field: 'englishProductName', width: 120, title: '英文品名'},
            {field: 'customsDeclarationUnit', width: 120, title: '报关单位'},
            {field: 'importTariffs', width: 120, title: '进口关税'},
            {field: 'taxRebateRate', width: 120, title: '退税率'},
            {field: 'vatRate', width: 120, title: '增值税率'},
            {field: 'outerPackingLong', title: '外包装长', width: 120},
            {field: 'outerPackingWide', title: '外包装宽', width: 120},
            {field: 'outerPackingHeight', title: '外包装高', width: 120},
            {field: 'outerPackingExplain', title: '外包装说明', width: 120},
            ]],
        page: false,
        limit: Number.MAX_VALUE,
        height: 380
        , done: function (res, curr, count) {
            hoverOpenImg();//显示大图
            //字段权限控制
            if(!isOrderInquiryTab){
                $("[data-field='unitPrice']").css('display','none');
                $("[data-field='moneySubtotal']").css('display','none');
            }
        }
    });

    //监听行单击事件
    table.on('row(storageproductstable)', function(obj){
        $("#hidden").show();
        let initParts = [];
        if(!isEmpty(obj.data.partsList)){
            initParts = obj.data.partsList;
        }
        table.render({
            elem: '#productsaselect'
            ,data:initParts
            ,toolbar: '#productsatoolbar'
            ,cols: [[
                {field: 'partsCode', title: '配件编码'}
                , {field: 'specNo', title: '规格编码'}
                , {field: 'proportionFinishedProducts', title: '成品比例'}
                , {field: 'partsFinishedProducts', title: '配件比例'}
                , {field: 'partsAmount', title: '数量'}
                , {field: 'productCname', title: '中文名称'}
                , {field: 'productEname', title: '英文名称'}
                , {field: 'grossWeight', title: '毛重'}
                , {field: 'netWeight', title: '净重'}
                , {field: 'bulk', title: '体积'}
            ]]
            ,id: 'productsatableid'
            ,page: false
            ,limit: Number.MAX_VALUE
            ,height:300
        });

        table.render({
            elem: '#istatusselect'
            ,url:"exportContract/getInventoryStatus"
            , toolbar: '#istatustoolbar'
            , where: {
                productCode: obj.data.productCode,
                specificationCode: obj.data.specificationCode
            }
            , cols: [[
                {field: 'productCode', title: '产品编码', sort: true}
                , {field: 'specificationCode', title: '规格编码', sort: true}
                , {field: 'lotNo', title: '批号', sort: true}
                , {field: 'realQuantity', title: '实际库存', sort: true}
                , {field: 'warehouseName', title: '仓库名称', sort: true}
                , {field: 'realAvailableQuantity', title: '实际可用', sort: true}
                , {field: 'contractNo', title: '合同号', sort: true}
                , {field: 'contractTypeStr', title: '类型', sort: true}
            ]]
            , id: 'istatustableid'
            , page: true
            , height: 300
        });
    });

    function hoverOpenImg() {
        var img_show = null; // tips提示
        $("body").delegate("td img", "mouseover", function () {
            var img = "<img class='img_msg' src='" + $(this).attr('src') + "' style='width:130px;' />";
            img_show = layer.tips(img, this, {
                tips: [2, 'rgba(41,41,41,.5)']
                , area: ['160px']
            });
        });
        $("body").delegate("td img", "mouseout", function () {
            layer.close(img_show);
        });
    }
    table.on('toolbar(istatustable)', function (obj) {
        var checkStatus = table.checkStatus(obj.config.id);
        switch (obj.event) {
            case 'refresh':
                table.reload('istatustableid',{data : oldData});
                break;
        };
    });

    //---费用
    table.render({
        elem: '#cost'
        , data: costList
        , toolbar: '#costtoolbar'
        , cols: [[
            {field: 'typeName', title: '费用类型'}
            , {field: 'amount', title: '金额',event:'amount',sort:'true'}
            , {field: 'memo', title: '备注说明',sort:'true'}
        ]]
        , id: 'costtableid'
        , height: 380
        ,page: false
        ,limit: Number.MAX_VALUE
    });

    //---附件
    table.render({
        elem: '#attachment'
        , data: annexList
        // , toolbar: '#attachmenttoolbar'
        , cols: [[
            {field: 'fileName', event:'fileName', title: '文件名', fixed: true}
            , {field: 'uploadTime', title: '上传日期', fixed: true, sort:true}
            , {fixed: 'right', width: 180, align: 'center', toolbar: '#attachmenteditor', title: '操作'}
        ]]
        , id: 'attachmenttableid'
        , height: 380
        , page: false
        , limit: Number.MAX_VALUE
        , done: function (res, index, upload) {
            let data = res.data;
            for(let i in data){
                let flag = true;
                for(let j in annexList){
                    if(data[i].id == annexList[j].id){
                        flag = false;
                        break;
                    }
                }
                if(flag){
                    annexList.push(data[i]);
                }
            }
        }
    });
    upload.render({
        elem: '#uploadfile'
        , url: 'transfer/uploadFile'
        , field: "uploadify"
        , accept: 'file'
        , multiple: true
        , auto: false
        , bindAction: '#testListAction'
        , choose: function (obj) {
            var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
            //读取本地文件
            obj.preview(function (index, file, result) {
                var tr = $(['<tr id="upload-' + index + '">'
                    , '<td>' + file.name + '</td>'
                    , '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
                    , '<td>等待上传</td>'
                    , '<td>'
                    , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                    , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                    , '</td>'
                    , '</tr>'].join(''));

                //单个重传
                tr.find('.demo-reload').on('click', function () {
                    obj.upload(index, file);
                });

                //删除
                tr.find('.demo-delete').on('click', function () {
                    delete files[index]; //删除对应的文件
                    tr.remove();
                    uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                });

                $("#uploadlist").append(tr);
            });
        }
        , parseData: function(res){
            return {
                "code": res.status,
                "count": res.total,
                "data": res.data
            };
        }
        , done: function (res, index, upload) {
            let data = res.data;
            for(var i in data){
                if (data[i].status) { //上传成功
                    annexList.push(data[i]);
                    var tr = $("#uploadlist").find('tr#upload-' + index)
                        , tds = tr.children();
                    tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                    tds.eq(3).html(''); //清空操作
                    return delete this.files[index]; //删除文件队列已经上传成功的文件
                }
                this.error(index, upload);
            }
        }
        , error: function (index, upload) {
            var tr = $("#uploadlist").find('tr#upload-' + index)
                , tds = tr.children();
            tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
            tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
        }
    });

    table.on('toolbar(attachmenttable)', function (obj) {
        switch (obj.event) {
            case 'uploadfile':
                $("#uploadlist").html(""); //清空上传列表数据
                layer.open({
                    type: 1,
                    title: "文件上传",
                    area: ['710px', '340px'],
                    content: $("#attachmentupload")//引用的弹出层的页面层的方式加载修改界面表单
                    , cancel: function (index, layero) {
                        //点击关闭刷新表格
                        table.reload('attachmenttableid', {data: annexList, limit: annexList.length});
                    }
                });
                break;
        };
    });
    table.on('tool(attachmenttable)', function (obj) {
        let data = obj.data;
        if (obj.event === 'download') { //下载
            let xmlHttpRequest = new XMLHttpRequest();
            let url = "wjinfo/downloadfile2?filename=" + data.filePath;
            xmlHttpRequest.open('GET', url, true);
            //设置请求头
            xmlHttpRequest.setRequestHeader("Content-type", "application/json")
            xmlHttpRequest.responseType = "blob";
            xmlHttpRequest.send(null);

            xmlHttpRequest.onload = function() {
                let content = xmlHttpRequest.response;
                // 组装a标签
                let elink = document.createElement("a");

                //设置文件下载路径
                elink.download = decodeURIComponent(data.fileName);
                elink.style.display = "none";
                let blob = new Blob([content], { type: 'application/force-download' });

                //解决下载不存在文件的问题，根据blob大小判断
                if(blob.size==0){
                    layer.msg('服务器没找到此文件，请联系管理员!');
                }else{
                    elink.href = window.URL.createObjectURL(blob);
                    document.body.appendChild(elink);
                    elink.click();
                    document.body.removeChild(elink);
                }

            }
        } else if (obj.event === 'del') {
            layer.confirm('确认删除?',
                confirmInfo(3,5), function (index) {
                    obj.del();
                    let id = data.id;
                    for (var i = 0; i < annexList.length; i++) {
                        if (annexList[i].id == id) {
                            if(0 == annexList[i]["news"]){
                                //记录被删除的老的附件
                                deleteAnnexIds.push(id);
                            }
                            annexList.splice(i, 1); // 将使后面的元素依次前移，数组长度减1
                            i--; // 如果不减，将漏掉一个元素
                            break;
                        }
                    }
                    layer.msg("删除成功", {icon: 6});
                    layer.close(index);
                    table.reload('attachmenttableid', {data:annexList}); //ajax删除成功之后刷新表格
                });
        } else if (obj.event === 'fileName') {
            onLineFile(data.filePath);
        }
    });

    //提示信息渲染
    function confirmInfo(icon, anim) {
        let data = {
            icon: icon,
            title: "提示",
            offset: "auto",
            skin: 'layui-layer-molv',
            anim: anim
        }
        return data;
    }

    //---操作日志
    table.render({
        elem: '#otherwarehouselog'
        , data: operationLog
        , cols: [[
              {field: 'operationType', title: '操作类型', fixed: true}
            , {field: 'operationName', title: '操作员'}
            , {field: 'operationTime', title: '操作日期'}
            , {field: 'operationContent', title: '修改内容'}
        ]]
        , id: 'logtableid'
        , height: 380
        , limit: 30//显示的数量
        , page: true
    });

    //字段是否为空或者零
    function isEmpty(obj){
        if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0){
            return true;
        }else{
            return false;
        }
    }

    //监听附件提交
    form.on('submit(form-element)', function (data) {

        let req = {};
        req["id"] = id;
        //该值取ModuleTypeEnum枚举类id
        req["type"] = 13;
        req["deleteAnnexIds"] = deleteAnnexIds;
        //获取附件数据
        let annexReqs = table.cache["attachmenttableid"];
        req["annexList"] = annexReqs;

        let datas = JSON.stringify(req);
        $.ajax({
            type:"POST",
            dataType:"json",
            contentType: 'application/json',
            data:datas,
            url:"basicInformation/annex/add",
            success:function(res){
                if(res.status == 200){
                    layer.msg("保存成功", {icon: 6});
                    setTimeout(function () {
                        //保存成功则刷新提交过来的界面 并关闭此页面
                        parent.detab("views/jsp/ExportBusiness/export.jsp");
                        parent.intab("views/jsp/ExportBusiness/export.jsp", "外销")
                        parent.detab("views/jsp/ExportBusiness/tpl/viewexport.jsp" + (id == '' ? '' : '?id=' + id));
                    }, 1000);
                }else {
                    layer.msg(res.msg, {icon: 5});
                }
                return false;
            }
        });
    });